package com.incar.chuxing.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.certification.CertifyCardActivity;
import com.incar.chuxing.activity.certification.CertifyDrivelicenseActivity;
import com.incar.chuxing.activity.driving.DrivingActivity;
import com.incar.chuxing.activity.personal.LoginActivity;
import com.incar.chuxing.adapter.DeliverRvAdapter;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.AbatementMoneyBean;
import com.incar.chuxing.bean.AddPreOrder;
import com.incar.chuxing.bean.AppConstants;
import com.incar.chuxing.bean.DeliverPriceBean;
import com.incar.chuxing.bean.ExistingTravel;
import com.incar.chuxing.bean.PreOrderDetailBean;
import com.incar.chuxing.bean.QualificationBean;
import com.incar.chuxing.bean.ZhiMaShouQuanBean;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.DensityUtils;
import com.incar.chuxing.utils.Dialogs.ConfirmAbatementDialog;
import com.incar.chuxing.utils.Dialogs.DialogOneButton;
import com.incar.chuxing.utils.Dialogs.DialogTwoButton;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.SystemToastUtils;
import com.incar.chuxing.utils.TimeUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.widget.MyTimePicker;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DeliverCarActivity extends BaseActivity implements MyTimePicker.OnTimeChosenListener {
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_name)
    TextView titleName;
    @BindView(R.id.title_more)
    ImageView titleMore;
    @BindView(R.id.title_tv_more)
    TextView titleTvMore;
    @BindView(R.id.deliver_useCar_tabA_tv0)
    TextView deliverUseCarTabATv0;
    @BindView(R.id.deliver_useCar_tabA_tv1)
    TextView deliverUseCarTabATv1;
    @BindView(R.id.deliver_useCar_tabA_iv)
    ImageView deliverUseCarTabAIv;
    @BindView(R.id.deliver_useCar_tabA)
    RelativeLayout deliverUseCarTabA;
    @BindView(R.id.deliver_useCar_tabB_tv0)
    TextView deliverUseCarTabBTv0;
    @BindView(R.id.deliver_useCar_tabB_tv1)
    TextView deliverUseCarTabBTv1;
    @BindView(R.id.deliver_useCar_tabB_iv)
    ImageView deliverUseCarTabBIv;
    @BindView(R.id.deliver_useCar_tabB)
    RelativeLayout deliverUseCarTabB;
    @BindView(R.id.deliver_useCar_tvLoc)
    TextView deliverUseCarTvLoc;
    @BindView(R.id.deliver_useCar_rlLoc)
    RelativeLayout deliverUseCarRlLoc;
    @BindView(R.id.deliver_useCar_min_tvTime)
    TextView deliverUseCarMinTvTime;
    @BindView(R.id.deliver_useCar_min_rlTime)
    RelativeLayout deliverUseCarMinRlTime;
    @BindView(R.id.deliver_useCar_min_tvTimeTip)
    TextView deliverUseCarMinTvTimeTip;
    @BindView(R.id.deliver_useCar_max_tvTimeTip)
    TextView deliverUseCarMaxTvTimeTip;
    @BindView(R.id.deliver_useCar_max_tv_startDate)
    TextView deliverUseCarMaxTvStartDate;
    @BindView(R.id.deliver_useCar_max_tv_startTime)
    TextView deliverUseCarMaxTvStartTime;
    @BindView(R.id.deliver_useCar_max_ll_start)
    LinearLayout deliverUseCarMaxLlStart;
    @BindView(R.id.deliver_useCar_max_tv_days)
    TextView deliverUseCarMaxTvDays;
    @BindView(R.id.deliver_useCar_max_ll_medium)
    LinearLayout deliverUseCarMaxLlMedium;
    @BindView(R.id.deliver_useCar_max_tv_endDate)
    TextView deliverUseCarMaxTvEndDate;
    @BindView(R.id.deliver_useCar_max_tv_endTime)
    TextView deliverUseCarMaxTvEndTime;
    @BindView(R.id.deliver_useCar_max_ll_end)
    LinearLayout deliverUseCarMaxLlEnd;
    @BindView(R.id.deliver_useCar_max_rlTime)
    RelativeLayout deliverUseCarMaxRlTime;
    @BindView(R.id.deliver_useCar_min_rgTime)
    RadioGroup deliverUseCarMinRgTime;
    @BindView(R.id.deliver_useCar_tvGradeTip)
    TextView deliverUseCarTvGradeTip;
    @BindView(R.id.deliver_useCar_rule)
    TextView deliverUseCarRule;
    @BindView(R.id.deliver_useCar_rv_grade)
    RecyclerView deliverUseCarRvGrade;
    @BindView(R.id.deliver_useCar_tvMoney)
    TextView deliverUseCarTvMoney;
    @BindView(R.id.deliver_useCar_llMoney)
    LinearLayout deliverUseCarLlMoney;
    @BindView(R.id.deliver_useCar_tvFreeTip)
    TextView deliverUseCarTvFreeTip;
    @BindView(R.id.checkbox)
    CheckBox abatementCheckBox;
    @BindView(R.id.car_detail_insure_tv)
    public TextView carDetailInsureTv;
    @BindView(R.id.car_detail_rent)
    TextView carDetailRent;
    @BindView(R.id.deliver_useCar_min_Time)
    RelativeLayout deliver_useCar_min_Time;
    private Context mContext = this;
    private DeliverRvAdapter deliverRvAdapter;
    private JSONArray gradeId;
    private LatLng useCarLoc;
    private String useCarAddress;
    private String preOrderTime, preOrderTimeEnd;
    public int rentType;//2日租，5小日租
    private List<AppConstants.DataBean.RentalLittleDaysOptionsBean> littleDaysOptionsBeans = new ArrayList<>();
    private MyTimePicker timePicker;
    private int selectType;
    private boolean checkChanged = false;
    private int dayNum;

    @Override
    public int getLayoutId() {
        return R.layout.activity_deliver_car;
    }

    @Override
    public void initView() {

        //获取不计免赔等信息
        rentType = 5;
        getAbatementmoney(rentType);

        //初始化不计免赔勾选项
        if (TextUtils.isEmpty(SPUtils.getInstance(mContext).getStringValue(SPKey.ABATEMENT_CHECK)) ||
                SPUtils.getInstance(mContext).getStringValue(SPKey.ABATEMENT_CHECK).equals("0")) {
            abatementCheckBox.setChecked(false);
        } else {
            abatementCheckBox.setChecked(true);
        }
        //小日租时长设置
        littleDaysOptionsBeans = new Gson().fromJson(SPUtils.getInstance(mContext).getStringValue(SPKey.LITTLE_DAY_RENT_OPTIONS_DURATION, "[{\"id\":\"1\",\"text\":\"4小时\"},{\"id\":\"2\",\"text\":\"8小时\"},{\"id\":\"3\",\"text\":\"12小时\"}]"), new TypeToken<List<AppConstants.DataBean.RentalLittleDaysOptionsBean>>() {
        }.getType());
        deliverUseCarMinRgTime.removeAllViews();
        for (int i = 0; i < littleDaysOptionsBeans.size(); i++) {
            //RadioButton radioButton = new RadioButton(mContext);//每次创建新的radioButton
            RadioButton radioButton = (RadioButton) View.inflate(mContext, R.layout.item_deliver_time_rv, null);
            radioButton.setId(i);
            radioButton.setWidth(DensityUtils.dp2px(mContext, 40));
            radioButton.setHeight(DensityUtils.dp2px(mContext, 40));
            radioButton.setText(littleDaysOptionsBeans.get(i).getText().substring(0, littleDaysOptionsBeans.get(i).getText().toString().indexOf("小")));
            RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(20, 0, 20, 0);
            radioButton.setLayoutParams(layoutParams);
            deliverUseCarMinRgTime.addView(radioButton, i);
        }
        deliverUseCarMinRgTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                checkChanged = true;
                dayNum = Integer.parseInt(littleDaysOptionsBeans.get(checkedId).getId());
                Logger.i("deliver", "###--" + deliverUseCarMinRgTime.getCheckedRadioButtonId() + "###--" + checkedId);
                try {
                    if ("8小时".equals(littleDaysOptionsBeans.get(checkedId).getText())) {
                        deliverUseCarTvFreeTip.setVisibility(View.VISIBLE);
                    } else {
                        deliverUseCarTvFreeTip.setVisibility(View.GONE);
                    }
                    if (TextUtils.isEmpty(deliverUseCarMinTvTime.getText().toString())) {
                        //SystemToastUtils.makeText(mContext, "请选择送车上门时间", ToastUtils.LENGTH_SHORT).show();
                    } else {
                        getRentCarPrice();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getDoubleExtra("lat", 0) != 0 && intent.getDoubleExtra("lng", 0) != 0) {
            useCarAddress = intent.getStringExtra("searchParkName") + "";
            useCarLoc = new LatLng(intent.getDoubleExtra("lat", 0), intent.getDoubleExtra("lng", 0));
            deliverUseCarTvLoc.setText(useCarAddress);
        }
    }

    private void getAbatementmoney(int rentType) {
        showLoadingDialog();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            jsonObject.put("rentType", rentType);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getAbatementMoney(body).enqueue(new Callback<AbatementMoneyBean>() {
            @Override
            public void onResponse(Call<AbatementMoneyBean> call, Response<AbatementMoneyBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null && response.body().getStatus() == 200) {
                    try {
                        //时间选择器
                        long maxTime = System.currentTimeMillis() + Long.parseLong(response.body().getAttachment().getBookingCarDuration().getMax()) * 60 * 1000;
                        long minTime = System.currentTimeMillis() + Long.parseLong(response.body().getAttachment().getBookingCarDuration().getMin()) * 60 * 1000;
                        timePicker = new MyTimePicker(mContext, 20, minTime, maxTime);
                        timePicker.setOnTimeChosenListener(DeliverCarActivity.this);
                        //日租的时间配置
                        if (rentType == 2) {
                           /* Calendar calendar = Calendar.getInstance();
                            calendar.setTimeInMillis(minTime);
                            int start_year = calendar.get(Calendar.YEAR);
                            int start_month = calendar.get(Calendar.MONTH) + 1;// Java月份从0开始算
                            int start_day = calendar.get(Calendar.DAY_OF_MONTH);
                            int start_dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                            String start_week = TimeUtils.getWeek(start_dayOfWeek - 1);
                            Calendar calendarNow = Calendar.getInstance();
                            int yearNow = calendarNow.get(Calendar.YEAR);
                            int monthNow = calendarNow.get(Calendar.MONTH) + 1;// Java月份从0开始算
                            int dayNow = calendarNow.get(Calendar.DAY_OF_MONTH);
                            if (start_year == yearNow && start_month == monthNow && start_day == dayNow) {
                                start_week = "今天";
                            }
                            String start_time = TimeUtils.getFormatDate(minTime + "", "HH:mm");
                            deliverUseCarMaxTvStartDate.setText(start_month + "月" + start_day + "日");
                            deliverUseCarMaxTvStartTime.setText(start_week + "" + start_time);
                            Calendar end_calendar = Calendar.getInstance();
                            end_calendar.setTimeInMillis(maxTime);
                            int end_year = end_calendar.get(Calendar.YEAR);
                            int end_month = end_calendar.get(Calendar.MONTH) + 1;// Java月份从0开始算
                            int end_day = end_calendar.get(Calendar.DAY_OF_MONTH);
                            int end_dayOfWeek = end_calendar.get(Calendar.DAY_OF_WEEK);
                            String end_week = TimeUtils.getWeek(end_dayOfWeek - 1);
                            if (end_year == yearNow && end_month == monthNow && end_day == dayNow) {
                                end_week = "今天";
                            }
                            String end_time = TimeUtils.getFormatDate(maxTime + "", "HH:mm");
                            deliverUseCarMaxTvEndDate.setText(end_month + "月" + end_day + "日");
                            deliverUseCarMaxTvEndTime.setText(end_week + "" + end_time);*/
                        }
                        //不计免赔
                        LinearLayoutManager manager = new LinearLayoutManager(DeliverCarActivity.this);
                        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        deliverUseCarRvGrade.setLayoutManager(manager);
                        deliverRvAdapter = new DeliverRvAdapter(response.body().getAttachment().getGradeList(), mContext);
                        deliverUseCarRvGrade.setAdapter(deliverRvAdapter);
                        if (response.body().getAttachment().getGradeList().size() > 0) {
                            List<Double> list = new ArrayList<>();
                            for (int i = 0; i < response.body().getAttachment().getGradeList().size(); i++) {
                                list.add(Double.parseDouble(response.body().getAttachment().getGradeList().get(i).getAbatementMoney()));
                            }
                            double macAbatementMoney = Collections.max(list);
                            if (rentType == 2) {
                                carDetailInsureTv.setText(new DecimalFormat("不计免赔(#.##元/天)").format(macAbatementMoney));
                            } else {
                                carDetailInsureTv.setText(new DecimalFormat("不计免赔(#.##元/小时)").format(macAbatementMoney));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(Call<AbatementMoneyBean> call, Throwable t) {
                dismissLoadingDialog();
                SystemToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });

    }

    @OnClick({R.id.checkbox, R.id.car_detail_rent, R.id.title_back, R.id.deliver_useCar_tabA, R.id.deliver_useCar_tabB, R.id.deliver_useCar_tvLoc, R.id.deliver_useCar_rlLoc, R.id.deliver_useCar_min_rlTime, R.id.deliver_useCar_max_ll_start, R.id.deliver_useCar_max_ll_end, R.id.deliver_useCar_rule, R.id.deliver_useCar_llMoney})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.deliver_useCar_tabA:
                rentType = 5;
                getAbatementmoney(rentType);
                deliverUseCarTabA.setBackgroundResource(R.drawable.corner_blue_rl);
                deliverUseCarTabB.setBackgroundResource(R.drawable.corner_blue_rl_white);
                deliverUseCarTabATv0.setTextColor(Color.WHITE);
                deliverUseCarTabATv1.setTextColor(Color.WHITE);
                deliverUseCarTabAIv.setImageResource(R.drawable.pic_dailyrent_hour_white);
                deliverUseCarTabBTv0.setTextColor(Color.parseColor("#A8B4C4"));
                deliverUseCarTabBTv1.setTextColor(Color.parseColor("#A8B4C4"));
                deliverUseCarTabBIv.setImageResource(R.drawable.pic_dailyrent_day_gray);
                deliverUseCarMinTvTimeTip.setVisibility(View.VISIBLE);
                deliverUseCarMaxTvTimeTip.setVisibility(View.GONE);
                deliver_useCar_min_Time.setVisibility(View.VISIBLE);
                deliverUseCarMinRlTime.setVisibility(View.VISIBLE);
                deliverUseCarMaxRlTime.setVisibility(View.GONE);
                deliverUseCarTvFreeTip.setVisibility(View.GONE);
                break;
            case R.id.deliver_useCar_tabB:
                rentType = 2;
                getAbatementmoney(rentType);
                deliverUseCarTabA.setBackgroundResource(R.drawable.corner_blue_rl_white);
                deliverUseCarTabB.setBackgroundResource(R.drawable.corner_blue_rl);
                deliverUseCarTabATv0.setTextColor(Color.parseColor("#A8B4C4"));
                deliverUseCarTabATv1.setTextColor(Color.parseColor("#A8B4C4"));
                deliverUseCarTabAIv.setImageResource(R.drawable.pic_dailyrent_day_gray);
                deliverUseCarTabBTv0.setTextColor(Color.WHITE);
                deliverUseCarTabBTv1.setTextColor(Color.WHITE);
                deliverUseCarTabBIv.setImageResource(R.drawable.pic_dailyrent_hour_white);
                deliverUseCarMinTvTimeTip.setVisibility(View.GONE);
                deliverUseCarMaxTvTimeTip.setVisibility(View.VISIBLE);
                deliver_useCar_min_Time.setVisibility(View.GONE);
                deliverUseCarMinRlTime.setVisibility(View.GONE);
                deliverUseCarMaxRlTime.setVisibility(View.VISIBLE);
                deliverUseCarTvFreeTip.setVisibility(View.GONE);
                break;
            case R.id.deliver_useCar_rlLoc:
            case R.id.deliver_useCar_tvLoc:
                Intent intent = new Intent(mContext, DeliverCarMapActivity.class);
                intent.putExtra("intentFrom", 0);
                startActivity(intent);
                break;
            case R.id.deliver_useCar_min_rlTime:
                if (timePicker != null) {
                    timePicker.showPicker();

                }
                break;
            case R.id.deliver_useCar_max_ll_start:
                selectType = 0;
                if (timePicker != null) {
                    timePicker.showPicker();

                }
                break;
            case R.id.deliver_useCar_max_ll_end:
                selectType = 1;
                if (timePicker != null) {
                    timePicker.showPicker();

                }
                break;
            case R.id.deliver_useCar_rule:
                Intent intent1 = new Intent();
                intent1.setClass(mContext, WebViewActivity.class);
                intent1.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "计价规则");
                intent1.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_valuation_car_total));
                startActivity(intent1);
                break;
            case R.id.deliver_useCar_llMoney:
                startActivity(new Intent(mContext, DeliverFeeDetailActivity.class));
                break;
            case R.id.checkbox:
                break;
            case R.id.car_detail_rent:
                judgeRentCar();
        }
    }

    @Override
    public void onTimeChosen(long millseconds) {
        Logger.i("deliver", millseconds + "");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millseconds);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;// Java月份从0开始算
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        String week = TimeUtils.getWeek(dayOfWeek - 1);
        Calendar calendarNow = Calendar.getInstance();
        int yearNow = calendarNow.get(Calendar.YEAR);
        int monthNow = calendarNow.get(Calendar.MONTH) + 1;// Java月份从0开始算
        int dayNow = calendarNow.get(Calendar.DAY_OF_MONTH);
        if (year == yearNow && month == monthNow && day == dayNow) {
            week = "今天";
        }
        String time = TimeUtils.getFormatDate(millseconds + "", "HH:mm");
        if (rentType == 5) {//小日租
            preOrderTime = millseconds + "";
            deliverUseCarMinTvTime.setText(week + " " + time);
            if (!TextUtils.isEmpty(deliverUseCarMinTvTime.getText().toString()) && checkChanged) {
                getRentCarPrice();
            }
        } else {
            if (selectType == 0) {
                preOrderTime = millseconds + "";
                deliverUseCarMaxTvStartDate.setText(month + "月" + day + "日");
                deliverUseCarMaxTvStartTime.setText(week + "" + time);
            } else {
                preOrderTimeEnd = millseconds + "";
                deliverUseCarMaxTvEndDate.setText(month + "月" + day + "日");
                deliverUseCarMaxTvEndTime.setText(week + "" + time);
            }
            if (!TextUtils.isEmpty(deliverUseCarMaxTvStartTime.getText().toString()) && !TextUtils.isEmpty(deliverUseCarMaxTvEndTime.getText().toString())) {
                getRentCarPrice();
            }
        }
    }

    private void judgeRentCar() {
        try {
            if (TextUtils.isEmpty(deliverUseCarTvLoc.getText().toString())) {
                ToastUtils.makeText(mContext, "请选择用车地点！", ToastUtils.LENGTH_SHORT).show();
                return;
            }
            if (rentType == 5 && TextUtils.isEmpty(deliverUseCarMinTvTime.getText().toString())) {
                ToastUtils.makeText(mContext, "请选择送车上门时间！", ToastUtils.LENGTH_SHORT).show();
                return;
            }
            if (rentType == 5 && !checkChanged) {
                ToastUtils.makeText(mContext, "请选择用车时长！", ToastUtils.LENGTH_SHORT).show();
                return;
            }
            if (rentType == 2 && (TextUtils.isEmpty(deliverUseCarMaxTvStartTime.getText().toString()) || TextUtils.isEmpty(deliverUseCarMaxTvEndTime.getText().toString()))) {
                ToastUtils.makeText(mContext, "请选择用车时间！", ToastUtils.LENGTH_SHORT).show();
                return;
            }
            //车辆等级不计免赔计算；
            int j = 0;
            gradeId = new JSONArray();
            if (deliverRvAdapter.getData() != null && deliverRvAdapter.getData().size() > 0) {
                for (int i = 0; i < deliverRvAdapter.getData().size(); i++) {
                    if (deliverRvAdapter.getData().get(i).isChecked()) {
                        j++;
                        gradeId.put(deliverRvAdapter.getData().get(i).getGradeId() + "");
                    }
                }
                if (j == deliverRvAdapter.getData().size()) {
                    tipCheckAbatement();
                } else if (j == 0) {
                    ToastUtils.makeText(mContext, "请选择车辆等级", ToastUtils.LENGTH_SHORT).show();
                } else {
                    DialogTwoButton dialogTwoButton = new DialogTwoButton(mContext);
                    dialogTwoButton.setTitle("提醒");
                    dialogTwoButton.setMessage("同时呼叫多种等级车辆，应答更快，您确认继续吗?");
                    dialogTwoButton.setNoOnclickListener("继续操作", new DialogTwoButton.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            dialogTwoButton.dismiss();
                            tipCheckAbatement();
                        }
                    });
                    dialogTwoButton.setYesOnclickListener("同时呼叫", new DialogTwoButton.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {
                            deliverUseCarRvGrade.setAdapter(deliverRvAdapter);
                            for (int i = 0; i < deliverRvAdapter.getData().size(); i++) {
                                deliverRvAdapter.getData().get(i).setChecked(true);
                            }
                            judgeRentCar();
                            dialogTwoButton.dismiss();
                        }
                    });
                    dialogTwoButton.show();
                }
            } else {
                ToastUtils.makeText(mContext, "请选择车辆等级", ToastUtils.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getRentCarPrice() {
        //调用接口获取费用
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            bodyJson.put("rentType", rentType);
            bodyJson.put("preOrderTime", preOrderTime);
            bodyJson.put("rentEndTime", preOrderTimeEnd);
            bodyJson.put("dayNum", dayNum);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getOrderFee(body).enqueue(new Callback<DeliverPriceBean>() {
            @Override
            public void onResponse(Call<DeliverPriceBean> call, Response<DeliverPriceBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        deliverUseCarTvMoney.setText(response.body().getAttachment().getRentMoney());
                        deliverUseCarMaxTvDays.setText(response.body().getAttachment().getPreRentTime());
                        if (rentType == 2) {

                        } else {

                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<DeliverPriceBean> call, Throwable t) {

            }
        });
    }

    private void rentCar() {
        showLoadingDialog();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            jsonObject.put("isAbatement", abatementCheckBox.isChecked() ? "1" : "2");
            jsonObject.put("dayNum", dayNum);
            jsonObject.put("preOrderTime", preOrderTime);
            jsonObject.put("gradeId", gradeId);
            jsonObject.put("rentType", rentType);
            jsonObject.put("endCarTime", preOrderTimeEnd);
            jsonObject.put("userAddress", useCarAddress);
            jsonObject.put("userLat", useCarLoc.latitude + "");
            jsonObject.put("userLng", useCarLoc.longitude + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).addPreOrder(body).enqueue(new Callback<AddPreOrder>() {
            @Override
            public void onResponse(Call<AddPreOrder> call, Response<AddPreOrder> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        Intent intent1 = new Intent();
                        intent1.setClass(mContext, DeliverCarMapActivity.class);
                        intent1.putExtra("intentFrom", 1);
                        intent1.putExtra("preOrderId", response.body().getAttachment().getPreOrderId());
                        startActivity(intent1);
                        AppManager.getAppManager().finishActivity();
                    } else if (response.body().getStatus() == 401) {
                        checkUserCertifyStatus();
                    } else if (response.body().getStatus() == 402 || response.body().getStatus() == 403) {
                        checkUserCertifyStatus();
                    } else if (response.body().getStatus() == 405) {

                        final DialogTwoButton inCarDialog = new DialogTwoButton(DeliverCarActivity.this);
                        inCarDialog.setTitle("提示");
                        inCarDialog.setMessage(response.body().getMessage());
                        inCarDialog.setYesOnclickListener("去往我的钱包", new DialogTwoButton.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Intent intent_wallet = new Intent(mContext, WebViewActivity.class);
                                intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的钱包");
                                CookieManager cookieManager2 = CookieManager.getInstance();
                                cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "isExist=" + SPUtils.getInstance(mContext).getIntValue(SPKey.DOT_ISEXITE));
                                cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "RushedSendPicture=" + SPUtils.getInstance(mContext).getStringValue(SPKey.WALLET_PICTURE));
                                intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet));
                                startActivity(intent_wallet);
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.setCancelable(false);
                        inCarDialog.show();
                    } else if (response.body().getStatus() == 409) {
                        final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                        inCarDialog.setTitle("提示");
                        inCarDialog.setMessage(response.body().getMessage());
                        inCarDialog.setYesOnclickListener("去认证", new DialogTwoButton.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Intent intent = new Intent(mContext, WebViewActivity.class);
                                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_margin_certification));
                                startActivity(intent);
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.show();

                    } else if (response.body().getStatus() == 410) {
                        final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                        inCarDialog.setTitle("提示");
                        inCarDialog.setMessage(response.body().getMessage());
                        inCarDialog.setYesOnclickListener("去认证", new DialogTwoButton.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                getZhiMaShouQuanUrl();
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.show();
                    } else if (response.body().getStatus() == 413) {
                        final DialogTwoButton inCarDialog = new DialogTwoButton(DeliverCarActivity.this);
                        inCarDialog.setTitle("您有未处理的违章");
                        inCarDialog.setMessage("请您处理后再用车");
                        inCarDialog.setYesOnclickListener("查看详情", new DialogTwoButton.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Intent intent_weizhang = new Intent(mContext, WebViewActivity.class);
                                intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "违章查询");
                                intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_break_rules));
                                startActivity(intent_weizhang);
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.setNoOnclickListener("好的", new DialogTwoButton.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.setCancelable(false);
                        inCarDialog.show();
                    } else if (response.body().getStatus() == 414) {
                        final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                        inCarDialog.setTitle("信用等级不足");
                        inCarDialog.setMessage("是否升级信用等级？");
                        inCarDialog.setYesOnclickListener("了解一下", () -> {
                            Intent intent = new Intent();
                            intent.setClass(mContext, WebViewActivity.class);
                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_success_identity));
                            startActivity(intent);
                            inCarDialog.dismiss();
                        });
                        inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
                        inCarDialog.show();
                    } else if (response.body().getStatus() == 418) {
                        dismissLoadingDialog();
                        startActivity(new Intent(mContext, CertifyDrivelicenseActivity.class));
                    } else {
                        final DialogOneButton inCarDialog = new DialogOneButton(mContext);
                        inCarDialog.setTitle("订车失败");
                        inCarDialog.setMessage(response.body().getMessage());
                        inCarDialog.setYesOnclickListener("知道了", new DialogOneButton.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.show();
                    }
                } else {
                    SystemToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AddPreOrder> call, Throwable t) {
                dismissLoadingDialog();
                SystemToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void tipCheckAbatement() {
        if (abatementCheckBox.isChecked()) {//勾选了不计免赔
            hasExistingTravelBeforeRent();
        } else {//未勾选
            ConfirmAbatementDialog confirmAbatementDialog = new ConfirmAbatementDialog(mContext);
            confirmAbatementDialog.setData(carDetailInsureTv.getText().toString().substring(4));
            confirmAbatementDialog.setOnCheckResultListener(new ConfirmAbatementDialog.OnCheckResultListener() {
                @Override
                public void onCheckDefault() {
                    SPUtils.getInstance(mContext).putStringValue(SPKey.ABATEMENT_CHECK, "1");
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    //deliverUseCarTvMoney.setText(deliverUseCarTvMoney.getText() + carDetailInsureTv.getText().toString().substring());
                    hasExistingTravelBeforeRent();

                }

                @Override
                public void onCheckNo() {
                    abatementCheckBox.setChecked(false);
                    confirmAbatementDialog.dismiss();
                    hasExistingTravelBeforeRent();
                }

                @Override
                public void onCheckOnce() {
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    hasExistingTravelBeforeRent();

                }

                @Override
                public void onCheckOk() {
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    hasExistingTravelBeforeRent();
                }
            });
            confirmAbatementDialog.show();
        }

    }

    /**
     * 检查是否有进行中的行程
     */
    private void hasExistingTravelBeforeRent() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getExistingTravel(((MyApplication) getApplication()).getRequestFieldMap())
                .enqueue(new Callback<ExistingTravel>() {
                    @Override
                    public void onResponse(Call<ExistingTravel> call, final Response<ExistingTravel> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (200 == response.body().getStatus()) {
                                if (response.body().getAttachment().getIsUnfinished() != 0) { //有进行中的行程
                                    String orderId = response.body().getAttachment().getOrderId();
                                    int rentType = response.body().getAttachment().getRentType();
                                    int bookType = response.body().getAttachment().getOrderModel().getBookType();
                                    //送车上门订单，派单中或送车中（已送达不）
                                    if (response.body().getAttachment().getPreOrder() != null) {
                                        String preOrderId = response.body().getAttachment().getPreOrder().getId();
                                        int preOrderStatus = response.body().getAttachment().getPreOrder().getStatus();
                                        if (!TextUtils.isEmpty(response.body().getAttachment().getPreOrder().getId())
                                                && (preOrderStatus == 0 || preOrderStatus == 1)) {
                                            final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(DeliverCarActivity.this);
                                            unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                            unFinishTravelDialog.setYesOnclickListener("进入", () -> {
                                                Intent intent = new Intent(mContext, WebViewActivity.class);
                                                CookieManager cookieManager = CookieManager.getInstance();
                                                cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo), "preOid=" + preOrderId);
                                                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo)
                                                        + "?preOid=" + preOrderId);
                                                startActivity(intent);
                                                unFinishTravelDialog.dismiss();
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", () -> unFinishTravelDialog.dismiss());
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                            return;
                                        }
                                    }


                                    // 其他订单
                                    switch (response.body().getAttachment().getStatus()) {
                                        case 10: {
                                            final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(DeliverCarActivity.this);
                                            unFinishTravelDialog.setMessage("您有未完成的行程，是否继续");
                                            unFinishTravelDialog.setYesOnclickListener("确定", new DialogTwoButton.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    Intent intentInUse = new Intent(mContext, DrivingActivity.class);
                                                    intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                                                    startActivity(intentInUse);
                                                    AppManager.getAppManager().finishActivity();
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                        }
                                        break;
                                        case 0: {
                                            final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(DeliverCarActivity.this);
                                            unFinishTravelDialog.setMessage("您有未完成的行程，是否继续");
                                            unFinishTravelDialog.setYesOnclickListener("确定", new DialogTwoButton.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    Intent intent = new Intent(mContext, MainActivity.class);
                                                    intent.putExtra("jumpCode", 4);
                                                    mContext.startActivity(intent);
                                                    AppManager.getAppManager().finishActivity();
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                        }
                                        break;
                                        case 15: {
                                            final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(DeliverCarActivity.this);
                                            unFinishTravelDialog.setTitle("有未支付的订单");
                                            unFinishTravelDialog.setMessage("支付后才能订车");
                                            unFinishTravelDialog.setYesOnclickListener("支付", new DialogTwoButton.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    Intent intent = new Intent(mContext, WebViewActivity.class);
                                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "订单支付");
                                                    CookieManager cookieManager = CookieManager.getInstance();
                                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "orderId=" + orderId);
                                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "oid=" + orderId);
                                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "rentType=" + rentType);
                                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "bookType=" + bookType);
                                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment) + "?oid=" + orderId + "&rentType=" + rentType + "&bookType=" + bookType);
                                                    startActivity(intent);
                                                    AppManager.getAppManager().finishActivity();
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                        }
                                        break;
                                    }

                                } else {//没有进行中订单
                                    rentCar();
                                }

                            } else if (20 == response.body().getStatus()) {
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                                Logger.d("netError", "查询进行中订单失败");
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                            Logger.d("netError", "查询进行中订单失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<ExistingTravel> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                        Logger.d("netError", "查询进行中订单失败  " + t);
                    }
                });
    }

    //验证用户汽车认证状态
    private void checkUserCertifyStatus() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getUserStatus(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<QualificationBean>() {
            @Override
            public void onResponse(Call<QualificationBean> call, Response<QualificationBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SPUtils.getInstance(mContext).putStringValue(SPKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_CAR_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_AMOUNT, response.body().getAttachment().getCarBail() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.JISHEN_STATUS, response.body().getAttachment().getStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_STATUS, response.body().getAttachment().getAuthorize() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_FEN, response.body().getAttachment().getScore() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.XINYONG_LEVEL, response.body().getAttachment().getLevel() + "");


                        int deposit = response.body().getAttachment().getDepositStatus();
                        int authorize = response.body().getAttachment().getAuthorize();
                        String licenseStatus = response.body().getAttachment().getLicenseStatus() + "";
                        if (authorize != 1 && deposit == 0) {
                            Intent intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_credit_auth));
                            startActivity(intent);
                        } else if ("11".equals(licenseStatus)) {
                            final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
                            dialogOneButton.setTitle("提示");
                            dialogOneButton.setMessage("身份信息审核中，请耐心等待");
                            dialogOneButton.setCancelable(false);
                            dialogOneButton.setCanceledOnTouchOutside(false);
                            dialogOneButton.setYesOnclickListener("确定", new DialogOneButton.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    dialogOneButton.dismiss();
                                }
                            });
                            dialogOneButton.show();
                        } else {
                            //未实名
                            Intent intent = new Intent(mContext, CertifyCardActivity.class);
                            startActivity(intent);
                        }
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<QualificationBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    public void getZhiMaShouQuanUrl() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getZhiMaAuthorizeUrl(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<ZhiMaShouQuanBean>() {
            @Override
            public void onResponse(Call<ZhiMaShouQuanBean> call, Response<ZhiMaShouQuanBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        dismissLoadingDialog();
                        String url = response.body().getAttachment().getUrl();
                        doVerify(url);
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ZhiMaShouQuanBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 启动支付宝进行认证
     *
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (hasApplication()) {
            SPUtils.getInstance(mContext).putStringValue(SPKey.INTENT_ZHIMA, "DeliverCarActivity");
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            // 这里使用固定appid 20000067
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivity(action);
        } else {
            // 处理没有安装支付宝的情况
            new AlertDialog.Builder(this)
                    .setMessage("是否下载并安装支付宝完成认证?")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent action = new Intent(Intent.ACTION_VIEW);
                            action.setData(Uri.parse("https://m.alipay.com"));
                            startActivity(action);
                        }
                    }).setNegativeButton("算了", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        }
    }

    /**
     * 判断是否安装了支付宝
     *
     * @return true 为已经安装
     */
    private boolean hasApplication() {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }
}
